// minepackage/pages/manage/manage.js
import { getLoginData, exitLogin, logOffAccount } from '../../api/manageApi'
import Dialog from '@vant/weapp/dialog/dialog'
import Toast from '@vant/weapp/toast/toast'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userJSON: null,
    loginData: {
      registerDate: '1970-01-01 00:00:00',
      lastLoginTime: '1970-01-01 00:00:00',
      loginNum: '0',
      experienceDay: '0'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const userDataStr = wx.getStorageSync('user_data')
    if (userDataStr == null || userDataStr == '') {
      wx.reLaunch({
        url: '/loginpackage/pages/login/login',
      })
    } else {
      this.setData({
        userJSON: JSON.parse(userDataStr)
      })
      wx.setNavigationBarTitle({
        title: '账号管理',
      })
      //获取登录数据
      this.getLoginDataRequest()
    }
  },

  /**
   * 获取登录信息
   */
  getLoginDataRequest() {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    })
    const params = {
      id: this.data.userJSON.id
    }
    //请求数据
    getLoginData(params, res => {
      this.setData({
        loginData: res.data
      })
    }, e => {
      console.log(e)
    })
  },

  /**
   * 退出登录
   */
  loginOutClick() {
    Dialog.confirm({
      title: '提示',
      message: '确认退出登录？',
    })
      .then(() => {
        const params = {
          id: this.data.userJSON.id
        }
        exitLogin(params, res => {
          if (res.msg === 'ok') {
            //清除token
            wx.removeStorageSync('token')
            //清除用户数据
            wx.removeStorageSync('user_data')
            //跳转到登录页
            wx.reLaunch({
              url: '/loginpackage/pages/login/login',
            })
          } else {
            Toast.fail('退出登录失败！');
          }
        }, e => {
          console.log(e)
        })
      })
      .catch(() => {
        // on cancel
      });
  },

  /**
   * 注销账号
   */
  logOffClick() {
    Dialog.confirm({
      title: '提示',
      message: '确认注销账号？',
    })
      .then(() => {
        const params = {
          id: this.data.userJSON.id
        }
        logOffAccount(params, res => {
          if (res.msg === 'ok') {
            //清除所有本地缓存
            wx.clearStorageSync()
            //跳转到登录页
            wx.reLaunch({
              url: '/loginpackage/pages/login/login',
            })
          } else {
            Toast.fail('注销账号失败！');
          }
        }, e => {
          console.log(e)
        })
      })
      .catch(() => {
        // on cancel
      });
  }

})